#include "pickonedlg.h"
#include "commonhelper.h"
#include <QPushButton>
#include <QHeaderView>
#include <QSqlQuery>
#include <QSqlError>
#include <QToolButton>
#include <QHBoxLayout>

PickOneDlg::PickOneDlg(QWidget *parent) : QWidget(parent)
{
    this->setWindowFlags(Qt::ToolTip);
    if (parent) {
        this->resize(parent->width() / 2, parent->height() / 2);
    }

    QHBoxLayout *hlayout = new QHBoxLayout;
    m_tableView = new QTableView(this);
    QToolButton *btnCancel = new QToolButton(this);
    btnCancel->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton));

    hlayout->addWidget(m_tableView);
    hlayout->addWidget(btnCancel);

    this->setLayout(hlayout);

    m_sqlModel = new QSqlQueryModel(this);

    connect(m_tableView, &QTableView::doubleClicked, this, &PickOneDlg::on_doubleClicked);
    connect(btnCancel, &QToolButton::clicked, this, &PickOneDlg::close);
}

void PickOneDlg::updateModel(const QString &recs)
{
//    setLists(recs);

    QString sql = "SELECT g.id, gb.barCode, g.simpleName, gu.Unitname, g.sellPrice FROM goods AS g, "
              "goodsUnit AS gu, goodsBarCode AS gb "
              "WHERE (g.id LIKE '%%1%' OR g.simpleName LIKE '%%2%' OR gb.barCode LIKE '%%3%') "
              "AND g.units = gu.id AND g.id = gb.goodId";

    sql = sql.arg(recs, recs, recs);
    QSqlQuery query(sql);
    query.exec();

    m_sqlModel->setQuery(query);
//    xdebug << query.isActive() << query.isForwardOnly();

    m_sqlModel->setHeaderData(0, Qt::Horizontal, "编码");
    m_sqlModel->setHeaderData(1, Qt::Horizontal, "条码");
    m_sqlModel->setHeaderData(2, Qt::Horizontal, "名称");
    m_sqlModel->setHeaderData(3, Qt::Horizontal, "单位");
    m_sqlModel->setHeaderData(4, Qt::Horizontal, "售价");

    m_tableView->setModel(m_sqlModel);

    m_tableView->horizontalHeader()->setHighlightSections(false); // 点击表头时不对表头高亮
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    m_tableView->horizontalHeader()->setStretchLastSection(true);
    m_tableView->resizeColumnsToContents();
}

void PickOneDlg::on_doubleClicked(const QModelIndex &index)
{
    QString id = m_tableView->model()->index(index.row(), 0).data().toString();
    emit picked(id);
    close();
}

void PickOneDlg::setLists(const QString &in)
{
    m_goodsIdList.clear();
    m_goodsNameList.clear();
    QSqlQuery query;
//    query.exec("SELECT id, simpleName FROM goods");
    query.exec("SELECT GoodsId, GoodsName FROM goods");
    while (query.next()) {
        QString id = query.value(0).toString();
        QString name = query.value(1).toString();
        if (id.contains(in)) {
            m_goodsIdList << id;
        }
        if (name.contains(in)) {
            m_goodsNameList << name;
        }
    }
}

